package com.fingard.dsp.bank.directbank.cbhb02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.cbhb02.utils.PacHostnameVerifier;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class CBHB02Base extends DirectBase {
    private String sessionMessage = null;
    private SSLSocketFactory sslSocketFactory = null;
    private HostnameVerifier hv = new PacHostnameVerifier();
    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }
    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.Time12Format.format(tmpDateNow);
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, CBHB02Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.transType)) {
            throw new Exception("未赋值transType");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.instSeq)) {
            throw new Exception("instSeq");
        }
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Cbhbpac");
        xmlWriter.writeElementAttribute("Message", "id", p_bankHeader.instSeq);
        xmlWriter.writeElementAttribute(p_bankHeader.transType + "Req", "id", p_bankHeader.transType + "Req");
        xmlWriter.writeElementString("version", p_bankHeader.version);//地区
        xmlWriter.writeElementString("instId", getBankConfig().getValueAsString("instId"));//请求时间
        xmlWriter.writeElementString("certId", getBankConfig().getValueAsString("certId"));//用户ID
        xmlWriter.writeElementString("serialNo", p_bankHeader.instSeq);//企业客户号
        xmlWriter.writeElementString("date", p_bankHeader.instDate);//交易码
    }
    protected String[] sendToBank(String p_reqStr) throws Exception {
        WriteBankLogStep2(p_reqStr);
        String[] retStr = new String[]{"", ""};
        String url = bankFront.serverURL;
        WriteBankLogLn("2.提交银行的地址：" + url);
        System.getProperties().put("java.protocol.handler.pkgs",
                "com.ibm.net.ssl.www2.protocol");
        URL myUrl = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) myUrl.openConnection();

        if (httpConn instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) httpConn;
            httpsConn.setHostnameVerifier(hv);
            httpsConn.setSSLSocketFactory(sslSocketFactory);
        }

        httpConn.setRequestMethod("POST");
        if (null != sessionMessage) {
            httpConn.setRequestProperty("Cookie", sessionMessage);
        }

        httpConn.setRequestProperty("Content-Type","application/xml;charset=utf-8");
        httpConn.setRequestProperty("Content-Length", p_reqStr.getBytes(getCharset()).length+"");
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setConnectTimeout(60000);
        httpConn.setReadTimeout(60000);
        httpConn.connect();
        OutputStream out = httpConn.getOutputStream();
        out.write(p_reqStr.getBytes(getCharset()));
        out.flush();
        out.close();

        String setCookie = httpConn.getHeaderField("Set-Cookie");

        if (null != setCookie) {
            int index = setCookie.indexOf(";");
            if (index > 0) {
                sessionMessage = setCookie.substring(0, index);
            } else {
                sessionMessage = setCookie;
            }
        }

        byte[] rspByte = readAllByteFromStream(httpConn.getInputStream());
        if (null != rspByte) {
            retStr[1] = new String(rspByte, getCharset());
            WriteBankLogStep3(retStr[1]);
        } else {
            retStr[0] = "-1";
            WriteBankLogStep3("can not read any content from server!");
        }

        httpConn.disconnect();

        return retStr;
    }
    public static byte[] readAllByteFromStream(InputStream is) throws Exception {
        byte[] buf = new byte[8072];

        ByteArrayOutputStream baos = new ByteArrayOutputStream(8072);
        int readCount = is.read(buf);
        while (readCount != -1) {
            baos.write(buf, 0, readCount);
            readCount = is.read(buf);
        }

        byte[] rsByte = baos.toByteArray();

        baos.close();
        baos = null;

        return rsByte;

    }
}
